package service.impl;

import bean.*;
import dao.impl.CartItemImpl;
import dao.impl.OrderDaoImpl;
import dao.impl.OrderItemImpl;
import service.OrderService;
import status.OrderStatus;

import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    OrderDaoImpl orderDao = new OrderDaoImpl();
    OrderItemImpl orderItem = new OrderItemImpl();
    CartItemImpl cartItem = new CartItemImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {

        String orderCode = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderCode, new Date(), cart.getTotalPrice(),
                OrderStatus.ORDER_STATUS_NOT_SHIPPED, userId, null);

        //创建订单
        orderDao.saveOrder(order);

        //创建订单详情
        for (CartItem item : cart.getItems()) {
            orderItem.saveOrderItem(new OrderItem(null, orderCode, item.getName(), item.getCount(),
                    item.getUnitPrice(), item.getTotalPrice()));
        }

        //清空购物车
        cartItem.clear(userId);

        return orderCode;
    }

    //    查找订单
    @Override
    public List<Order> showMyOrders(Integer userId) {
        try {
            return orderDao.queryOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

//   查看订单详情

    @Override
    public List<OrderItem> showOrderDetail(Long orderCode) {
        try {
            return orderItem.queryOrderItemByOrderCode(orderCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int orderStatusUpdate(String orderCode) {
        try {
     return orderDao.updateOrderStatus(orderCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
